import { createApp } from "vue";
import "./style.css";
import App from "./App.vue";
import router from "./router";
import * as ElementPlusIconsVue from "@element-plus/icons-vue";
import { createPinia } from "pinia";
import PanelHead from "./components/panelHead.vue";
import createPersistedstate from "pinia-plugin-persistedstate";
import { CounterStore } from "./store/index";
import type { RouteRecordRaw } from "vue-router";

const app = createApp(App);
const pinia = createPinia();
pinia.use(createPersistedstate);
app.use(pinia);

for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component);
}

// 前置路由守卫to当前所需要跳转的路径
router.beforeEach((to) => {
  // 在这里添加你的逻辑
  const token = localStorage.getItem("pz_token");
  const localData = localStorage.getItem("pz_v3pz");
  // 判断是否非登录页面token是否存在
  if (!token && !localData && to.path !== "/login") {
    return "/login";
  } else if (token && to.path === "/login") {
    return "/";
  } else {
    return true;
  }
});

// 刷新后的动态路由添加
const localData = localStorage.getItem("pz_v3pz");
const store = CounterStore();
if (localData) {
  // 将数据恢复到pinia中
  store.dynamicMenu(JSON.parse(localData).state.routerList);

  store.state.routerList.forEach((item: RouteRecordRaw) => {
    // 动态添加路由
    router.addRoute("main", item);    
  });
}

// 路由挂载
app.use(router);
app.mount("#app");
app.component("PanelHead", PanelHead);